import React from "react";
import { Upload, Button, Icon, message } from "antd";
import { getFileUrl } from "services/public.js";

const buttonStyle = {
  color: "#bfbfbf",
  // maxWidth: '198px',
  overflow: "hidden",
  textOverflow: "ellipsis",
  whiteSpace: "nowrap",
};
class CustomUploadField extends React.Component {
  static getDerivedStateFromProps(nextProps) {
    // Should be a controlled component.
    if ("value" in nextProps) {
      return {
        fileList: nextProps.value || [],
      };
    }
    return null;
  }

  constructor(props) {
    super(props);
    const { params = [] } = this.props;
    const { template } = params;
    const value = template || [];
    this.state = {
      fileList: value,
    };
    this.uploadProps = {
      action: "/flow-platform/file/add",
      onChange: this.onFileChange,
      beforeUpload: this.beforeUpload,
      defaultFileList: [],
    };
  }

  componentDidMount() {}

  componentWillUnmount() {}

  onFileChange = ({ file, fileList }) => {
    const { params } = this.props;

    if (params.multiple === false) {
      const isHas = fileList.some(ele => ele.status === "done");
      if (!isHas) {
        this.setState({ fileList });
        this.triggerChange(fileList);
      }
    } else {
      const urlList = fileList.map(ele => {
        if (ele.uid === file.uid && file.status === "done") {
          ele.url = getFileUrl(ele.response.datas);
          return ele;
        }
        return ele;
      });

      this.setState({ fileList: urlList });
      this.triggerChange(urlList);
    }
    // if (file.status !== "uploading") {
    //   this.triggerChange(fileList);
    // }
  };

  beforeUpload = () => {
    const { fileList } = this.state;
    const { params } = this.props;
    if (params.multiple === false) {
      const isHas = fileList.some(ele => ele.status === "done");
      if (isHas) {
        message.warn("不允许上传多个附件");
        return false;
      }
    }
    return true;
  };

  triggerChange = changedValue => {
    // Should provide an event to pass value to Form.
    const { onChange } = this.props;
    if (onChange) {
      onChange(changedValue);
    }
  };

  render() {
    const { uploadProps = {}, itemProps = {} } = this.props;
    const newProps = { ...this.uploadProps, ...uploadProps, ...itemProps };
    // console.log(newProps.disabled);
    if (newProps.disabled) {
      newProps.showUploadList = {
        showRemoveIcon: false,
      };
    }
    const { placeholder, contentpart, ...restProps } = itemProps;
    const { fileList } = this.state;
    const hint = placeholder || "上传文件";
    return (
      <Upload {...newProps} fileList={!contentpart && fileList}>
        <Button
          {...restProps}
          style={buttonStyle}
          // title={hint}
        >
          <Icon type="upload" />
          {hint}
        </Button>
      </Upload>
    );
  }
}
export default CustomUploadField;
